package com.owen.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.owen.pojo.Fenlei;
import com.owen.pojo.Order;
import com.owen.server.OrderServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/order")
public class OrderController {

    @Autowired
    private OrderServer orderServer;

    @ResponseBody
    @RequestMapping(value = "/fileExport")
    public void fileExport(Order order, HttpServletResponse response) throws ClassNotFoundException, IndexOutOfBoundsException, IOException {
        // 生成excel
        ExcelWriter writer = ExcelUtil.getWriter();
        // 数据库查询
        List<Order> byOrder = orderServer.findByOrder(order);
        List<Map<String, Object>> rows = byOrder.stream().map(item -> {
            Map<String, Object> maps = new HashMap<>();
            maps.put("id", item.getId() == null ? "" : item.getId().toString());
            maps.put("address", item.getAddress());
            maps.put("createtime", DateUtil.format(item.getCreatetime(),"yyyy-MM-dd"));
            maps.put("details", item.getDetails());
            maps.put("name", item.getName());
            maps.put("orderId", item.getOrderId() == null ? "" : item.getOrderId().toString());
            maps.put("phone", item.getPhone());
            maps.put("status", item.getStatus());
            maps.put("userId", item.getUserId() == null ? "" : item.getUserId().toString());
            maps.put("totalprice", item.getTotalprice() == null ? "" : item.getTotalprice().toString());
            maps.put("userName", item.getUserName());
            return maps;
        }).collect(Collectors.toList());

        // Title
        int columns = Class.forName("com.owen.pojo.Order").getDeclaredFields().length;
        writer.merge(columns - 1, "账单信息");
        // Header
        writer.addHeaderAlias("id", "主键ID");
        writer.addHeaderAlias("address", "地址");
        writer.addHeaderAlias("createtime", "下单时间");
        writer.addHeaderAlias("details", "描述");
        writer.addHeaderAlias("name", "商品名");
        writer.addHeaderAlias("orderId", "订单ID");
        writer.addHeaderAlias("phone", "电话");
        writer.addHeaderAlias("status", "状态");
        writer.addHeaderAlias("userId", "总价");
        writer.addHeaderAlias("totalprice", "用户ID");
        writer.addHeaderAlias("userName", "用户姓名");

        // Body
        writer.setColumnWidth(0, 30);
        writer.setColumnWidth(1, 30);
        writer.setColumnWidth(2, 30);
        writer.setColumnWidth(3, 30);
        writer.setColumnWidth(4, 30);
        writer.setColumnWidth(5, 30);
        writer.setColumnWidth(6, 30);
        writer.setColumnWidth(7, 30);
        writer.setColumnWidth(8, 30);
        writer.setColumnWidth(9, 30);
        writer.setColumnWidth(10, 30);
        writer.write(rows, true);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("账单信息-" + DateUtil.today() + ".xls", "utf-8"));
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
    }

    @RequestMapping(value = "/find", method = RequestMethod.GET)
    public String find() {
        PageHelper.startPage(1, 10);
        List<Order> orders = orderServer.findAll();
        PageInfo<Order> orderInfo = new PageInfo<>(orders);
        Map<String, Object> res = new HashMap<>();
        if(orders != null){
            res.put("code", "200");
            res.put("msg", "查询成功");
            res.put("data", orderInfo);
        } else {
            res.put("code", "201");
            res.put("msg", "查询失败");
        }
        String json = JSON.toJSONString(res);
        return json;
    }

    @RequestMapping(value = "/findByOrder", method = RequestMethod.GET)
    public String findByOrder(Order order, Integer xuanzhepage, String currentPage){

        // 获取页数
        Integer current = 1;
        if (currentPage != null) {
            current = Integer.valueOf(currentPage);
        }

        PageHelper.startPage(current, xuanzhepage);
        List<Order> orderList = orderServer.findByOrder(order);
        PageInfo<Order> ordisInfo = new PageInfo<>(orderList);

        Map<String, Object> res = new HashMap<>();
        if (Optional.ofNullable(orderList).isPresent()) {
            res.put("code", "200");
            res.put("msg", "查询成功");
            res.put("data", ordisInfo);
        } else {
            res.put("code", "201");
            res.put("msg", "查询失败");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

    @RequestMapping(value = "/deleteBatch", method = RequestMethod.POST)
    public String deleteBatch(Integer [] ids) {
        Map<String,Object> res = new HashMap<>();
        Integer count = orderServer.deleteBatch(ids);
        if (count > 0) {
            res.put("code", 200);
            res.put("msg", "删除成功！");
        }else {
            res.put("code", 201);
            res.put("msg", "删除失败！");
        }
        String json = JSON.toJSONString(res);
        return json;
    }

    @RequestMapping(value = "/findById/{id}", method = RequestMethod.GET)
    public String findById(@PathVariable("id") Integer id){
        Order order = orderServer.findById(id);
        Map<String, Object> res = new HashMap<>();
        if (Optional.ofNullable(order).isPresent()) {
            res.put("code", "200");
            res.put("msg", "查询成功");
            res.put("data", order);
        } else {
            res.put("code", "201");
            res.put("msg", "查询失败");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

    @RequestMapping(value = "/updateOrder/{id}")
    public String updateOrder(@PathVariable("id") Integer id){
        Integer integer = orderServer.updateOrder(id);
        Map<String, Object> res = new HashMap<>();
        if (integer > 0) {
            res.put("code", "200");
            res.put("msg", "发货成功");
        } else {
            res.put("code", "201");
            res.put("msg", "发货失败");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

}